import java.util.Hashtable;
import java.util.Timer;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

public class ScrWeather extends MIDlet
{
	static private boolean alreadyStarted;
	static private ScrWeatherScreen screen;
	static private WeatherReader reader;
	static private Timer timer = new Timer();
	static private Display display;
	static private OptionsForm optionsForm;
	
	public ScrWeather()
	{
	}

	protected void destroyApp(boolean arg0) throws MIDletStateChangeException
	{
		Options.save();
	}

	protected void pauseApp()
	{
	}

	protected void startApp() throws MIDletStateChangeException
	{
		if (!alreadyStarted)
		{
			display = Display.getDisplay(this); 
			Options.load();
			screen = new ScrWeatherScreen(display);
			display.setCurrent(screen);
			startTimer();
		} else
		{
		    setMinimized(false);
		}
		
		alreadyStarted = true;
	}
	
	static public void setMinimized(boolean mini)
	{
		if (mini)
		{
			display.setCurrent(null);
		} else
		{
			display.setCurrent(screen);
		}
	}

	public static void setResults(Hashtable results)
	{
		screen.showResults(results);
	}
	
	public static void loadPhenomenaImage(String imgName1, String imgName2)
	{
		screen.loadPhenomenaImage(imgName1, imgName2);
	}
	
	public static void refresh()
	{
		reader.cancel();
		startTimer();
	}
	
	private static void startTimer()
	{
		String cityNum = Integer.toString(Options.cityNum);
		reader = new WeatherReader(cityNum);
		timer.schedule(reader, 1000, Options.requestInterval*3600*1000);
	}
	
	private static int lastCity = 0;
	private static int lastReqInterval = 0;
	public static void showOptions()
	{
		lastCity = Options.cityNum;
		lastReqInterval = Options.requestInterval; 
		optionsForm = new OptionsForm();
		optionsForm.execute(display);
	}
	
	public static void upplyOptions(boolean ok)
	{
		optionsForm = null;
		if (ok)
		{
			Options.save();
			if ((lastCity != Options.cityNum) || (lastReqInterval != Options.requestInterval))
			{
				screen.showResults(null);
				refresh();
			}
		}
		display.setCurrent(screen);
		screen.repaint();
	}
}
